package com.maycurobj.service.http;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.ParseException;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;

import static com.maycurobj.util.NormalUtil.encodeUrl;

@Component
@Slf4j
public class HttpAPIService {

    @Autowired
    private CloseableHttpClient httpClient;

    @Autowired
    private RequestConfig config;

    @Value("${crm.url}")
    private String CRMURL;

    /**
     * 不带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doGet(String url) throws Exception {
        // 声明 http get 请求
        HttpGet httpGet = new HttpGet(url);

        // 装载配置信息
        httpGet.setConfig(config);

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);

        // 判断状态码是否为200
        if (response.getStatusLine().getStatusCode() == 200) {
            // 返回响应体的内容
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        response.close();
        return null;
    }

    /**
     * crm请求专用
     * @param url
     * @return
     * @throws Exception
     */
    public String doGetForCrm(String url)throws Exception {
        HttpGet httpGet = new HttpGet(url);
        // 装载配置信息
        httpGet.setConfig(config);

        RequestConfig requestConfig = RequestConfig.custom().setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM)).setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new NTCredentials("test", "Bio-San@123", CRMURL, "biosan"));
        this.httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).setDefaultRequestConfig(requestConfig).build();

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);

        // 判断状态码是否为200
        if (response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() <= 210) {
            // 返回响应体的内容
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        response.close();
        return null;
    }

    public String doGetForCrm(String url, String systemUserId, Integer pageSize) throws Exception {
        log.info("doGetCrm-请求URL(含userid):" + url);
        CloseableHttpResponse response = null;
        String ret = null;
        try {
            // 声明 http get 请求
            HttpGet httpGet = new HttpGet(url);
            // 装载配置信息
            httpGet.setConfig(config);
            if (StringUtils.isNotBlank(systemUserId)) {
                httpGet.addHeader("MSCRMCallerID", systemUserId);
            }
            if (!Objects.isNull(pageSize)) {
                httpGet.addHeader("Prefer", "odata.maxpagesize=" + pageSize);
            }
            RequestConfig requestConfig = RequestConfig.custom().setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM)).setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new NTCredentials("test", "Bio-San@123", "biosan", "biosan"));
            this.httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).setDefaultRequestConfig(requestConfig).build();
            // 发起请求
            response = this.httpClient.execute(httpGet);

            // 判断状态码是否为200
            if (response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() <= 210) {
                // 返回响应体的内容
                ret = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (IOException e) {
            log.info("doGetCrm 请求IO异常---->{}", e.toString());
        } catch (ParseException e) {
            log.info("doGetCrm 请求ParseException异常---->{}", e.toString());
        }
        response.close();
        return ret;
    }


    /**
     * 带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doGet(String url, Map<String, Object> map) throws Exception {
        URIBuilder uriBuilder = new URIBuilder(url);

        if (map != null) {
            // 遍历map,拼接请求参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // 调用不带参数的get请求
        return this.doGet(uriBuilder.build().toString());

    }

    /**
     * 带参数的post请求
     * 如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @param str
     * @return
     * @throws Exception
     */
    public String doPost(String url, String str) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response=null;
        // 加入配置信息
        httpPost.setConfig(config);

        if (str != null) {
            // 判断map是否为空，不为空则进行遍历，封装from表单对象
            StringEntity stringEntity = new StringEntity(str, "utf-8");
            stringEntity.setContentEncoding("UTF-8");
            httpPost.setEntity(stringEntity);
            httpPost.setHeader("Content-Type", "application/json;charset=utf-8");

            // 发起请求
             response = this.httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
            response.close();

        }
        return null;
    }

    /**
     * 带参数的post请求
     * 如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @param str
     * @param token
     * @return
     * @throws Exception
     */
    public String doPost(String url, String str,String token) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);
        CloseableHttpResponse response=null;

        if (str != null) {
            // 判断map是否为空，不为空则进行遍历，封装from表单对象
            StringEntity stringEntity = new StringEntity(str, "utf-8");
            stringEntity.setContentEncoding("UTF-8");
            httpPost.setEntity(stringEntity);
            httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
            httpPost.setHeader("Authorization","Bearer "+token);

            // 发起请求
             response = this.httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
            response.close();

        }
        return null;
    }

    public String doPostForEhr(String url, String str) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);
        CloseableHttpResponse response=null;
        if (str != null) {
            // 判断map是否为空，不为空则进行遍历，封装from表单对象
            StringEntity stringEntity = new StringEntity(str, "utf-8");
            stringEntity.setContentEncoding("UTF-8");
            httpPost.setEntity(stringEntity);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.setHeader("Connection","keep-alive");
            httpPost.setHeader("cache-control","no-cache");

            // 发起请求
            response = this.httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
            response.close();
        }
        return null;
    }


    /**
     * 不带参数的post 请求
     *
     * @param url
     * @throws Exception
     */
    public void doPost(String url) throws Exception {
        this.doPost(url, null);
    }

}
